<template>
  <basic-container>
    <!--    筛选条件-->
    <div class="header">
      <!--日期与模板-->
      <div class="header-up">
        <div class="date-template">
          <div class="dt-item">
<!--            <el-button size="mini" type="primary" @click="multipleInvestMoney(true)">充值</el-button>-->
            <el-button size="mini" type="primary" @click="approvedReview()">审核通过</el-button>
            <el-button size="mini" type="warning" @click="reviewReject()">审核拒绝</el-button>
            <el-button size="mini" type="primary" @click="batchRechargeSuccessfully()">充值成功</el-button>
            <el-button size="mini" type="warning" @click="failureRecharge()">充值失败</el-button>
            <el-button size="mini" type="danger" @click="multipleInvestMoney(false,'扣减')">扣减</el-button>
<!--            <el-button size="mini" @click="showDetail">充值记录</el-button>-->
          </div>
        </div>
        <div class="yesterday">{{ bcBalance.date }}当前BC可用余额 :{{ bcBalance.bc_balance }} USD</div>
        <el-popover
          placement="bottom-start"
          width="200"
          trigger="hover"
          :disabled="threeDayTip">
          <div class="popover_pane">
            <div>
              <i class="el-icon-info" style="color: orangered"></i>
              <strong> 3日告警</strong>
            </div>
            <span>
                当前账户的余额预计三日内消耗完
            </span>
          </div>
          <div slot="reference" :class="threeCostTip">3天预估花费 :{{ threeDaysPredictCost }} USD</div>
        </el-popover>
        <el-popover
          placement="bottom-start"
          width="200"
          trigger="hover"
          :disabled="sevenDayTip">
          <div class="popover_pane">
            <div>
              <i class="el-icon-info" style="color: orangered"></i>
              <strong> 7日告警</strong>
            </div>
            <span>
                当前账户的余额预计七日内消耗完
            </span>
          </div>
          <div slot="reference" :class="sevenCostTip">7天预估花费 :{{ sevenDaysPredictCost }} USD</div>
        </el-popover>

      </div>
      <el-form v-model="StatusSelection">
        <el-form-item label="充值状态" >
          <el-select v-model="StatusSelection.checked1" clearable size="mini" @change="newStatus">
            <el-option v-for="item in statusList" :label="item.label" :key="item.value" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="curd-table">
        <div class="tab-header clearfix" style="margin:10px 0 20px 30px ">
          <div class="tab-header-left">
            <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions" @change="handleChangeFilter">
            </cs-filter-query>
          </div>
        <div class="tab-header-right" style="margin-right: 30px">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button icon="el-icon-refresh" size="mini" circle @click="uploadAccount"></el-button>
          </el-tooltip>
        </div>
        </div>
      </div>
<!--      筛选充值状态:-->
<!--      <el-checkbox v-model="checked1" @change="newStatus" >新需求</el-checkbox>-->
<!--      <el-checkbox v-model="checked2" @change="newStatus1">进行中</el-checkbox>-->
<!--      <el-tooltip class="item" effect="dark" content="重置筛选" placement="top">-->
<!--        <el-button icon="el-icon-refresh" size="mini" circle @click="uploadAccount"></el-button>-->
<!--      </el-tooltip>-->
    </div>
    <!--    表格列-->
    <div class="curd-table">
      <div class="tab-header clearfix">
        <div class="tab-header-left">

        </div>
        <div class="tab-header-right">
        </div>
      </div>
      <div class="table-body">
        <el-table
          v-loading="loading"
          border
          ref="multipleTable"
          :data="accountList"
          :header-cell-style="iHeaderCellStyle"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="40">
          </el-table-column>
          <el-table-column
            label="序号"
            type="index"
            align="center">
          </el-table-column>
          <el-table-column
            prop="accountName"
            label="账户名称"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="platformId"
            label="账户ID"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="customerFullName"
            label="客户名称"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="amount"
            label="充值金额">
          </el-table-column>
          <el-table-column
            prop="platform"
            label="媒体">
          </el-table-column>
          <el-table-column
            prop="accountOperator"
            label="账户运营人"
            width="90">
          </el-table-column>
          <el-table-column
            prop="ttOneAgentTenantName"
            label="代理">
          </el-table-column>
          <el-table-column
            prop="level"
            label="优先级"
            :formatter="formatterLevel">
          </el-table-column>
          <el-table-column
            prop="status"
            label="充值状态"
            :formatter="formatterStatus">
          </el-table-column>
          <el-table-column
            prop="refusalCause"
            label="拒绝原因"
          :show-overflow-tooltip="true">
          </el-table-column>
<!--          <el-table-column-->
<!--            prop="requirementName"-->
<!--            label="需求人"-->
<!--            :formatter="formatterUserName">-->
<!--          </el-table-column>-->
          <el-table-column
            prop="auditUserName"
            label="审批人">
          </el-table-column>
          <el-table-column
            prop="auditTime"
            label="审批时间"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="申请时间"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="createUser"
            label="创建人"
            :formatter="formatterUserName">
          </el-table-column>
          <el-table-column
            label="操作" width="130" align="center" fixed="right">
            <template v-slot="{row}">

<!--              <el-tooltip content="充值" placement="top">-->
<!--                <el-button size="small" icon="el-icon-plus" type="text" @click="investMoney(true, row)"></el-button>-->
<!--              </el-tooltip>-->
<!--              <el-tooltip class="item" effect="dark" content="扣减" placement="top">-->
<!--                <el-button size="small" icon="el-icon-minus" type="text" @click="investMoney(false, row)"></el-button>-->
<!--              </el-tooltip>-->
<!--              <el-tooltip class="item" effect="dark" content="充值记录" placement="top">-->
<!--                <el-button size="small" icon="el-icon-copy-document" type="text"-->
<!--                           @click="getRecordById(row)"></el-button>-->
<!--              </el-tooltip>-->
              <el-tooltip class="item" effect="dark" content="审核通过" placement="top">
                <el-button size="small" icon="el-icon-check" type="text" @click="auditPass(row.id)" :disabled="row.status!==0"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="审核拒绝" placement="top">
                <el-button size="small" icon="el-icon-close" type="text" @click="batchAuditReject(row.id)" :disabled="row.status!==0"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="充值成功" placement="top">
                <el-button size="small" icon="myicon icon-topUpSusses" @click="rechargeSuccessfullyClick(row.id)" type="text"  :disabled="![0,1].includes(row.status) || row.platform == 'tiktok'"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="充值失败" placement="top">
                <el-button size="small" icon="myicon icon-topUpFailure" type="text"  @click="failureRechargeClick(row.id)"  :disabled="![0,1].includes(row.status) || row.platform == 'tiktok'"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom-page clearfix">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <!--   新增 -->
    <el-drawer
      :title="isEdit? isPlus? '充值':'扣减':'充值记录'"
      size="80%"
      :visible.sync="addDrawerSwitch"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
      @close="closeRecordsDrawer"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <div class="add-money-box">
          <div class="push-money-info" v-if="isPlus&&isEdit">
            <div class="push-money-info-left">
              <i class="el-icon-info"></i><span style="margin-left: 23px">请仔细核查账户充值信息，系统会根据账户的充值金额自动充值！</span>
            </div>
            <div class="push-money-info-right">
              <p>合计充值金额：{{ totalMoney }} USD</p>
              <p>当前可用金额：{{ bcBalance.bc_balance }} USD</p>
            </div>
          </div>
          <el-form ref="moneyForm" label-position="top" :model="moneyForm" label-width="80px" :rules="rules">
            <el-form-item>
              <el-table
                v-if="isEdit"
                :data="moneyForm.request"
                style="width: 100%"
                ref="moneyTable"
              >
                <el-table-column
                  prop="platformId"
                  :show-overflow-tooltip="true"
                  width="200"
                  label="账户ID">
                </el-table-column>
                <el-table-column
                  prop="accountName"
                  :show-overflow-tooltip="true"
                  label="账户名称">
                </el-table-column>
                <el-table-column
                  prop="customerFullName"
                  :show-overflow-tooltip="true"
                  label="客户名称">
                </el-table-column>
                <el-table-column
                  prop="platform"
                  label="媒体">
                </el-table-column>
                <el-table-column
                  prop="accountOperator"
                  label="账户运营人">
                </el-table-column>
                <el-table-column
                  prop="ttOneAgentTenantName"
                  label="代理">
                </el-table-column>
                <el-table-column
                  prop="limits"
                  label="账户余额">
                </el-table-column>
                <el-table-column
                  prop="amount"
                  label="充值金额"
                v-if="isPlus">
                </el-table-column>
                <el-table-column
                  prop="level"
                  label="优先级"
                  v-if="isPlus"
                  :formatter="formatterLevel">
                </el-table-column>
                <!--<el-table-column-->
                <!--  prop="requirementName"-->
                <!--  label="需求人"-->
                <!--  v-if="isEdit"-->
                <!--  :formatter="formatterUserName">-->
                <!--</el-table-column>-->
                <!--<el-table-column-->
                <!--  prop="status"-->
                <!--  label="状态"-->
                <!--  :formatter="formatterStatusMix">-->
                <!--</el-table-column>-->
                <!--<el-table-column-->
                <!--  prop="createTime"-->
                <!--  label="申请时间"-->
                <!--  :show-overflow-tooltip="true">-->
                <!--</el-table-column>-->
                <el-table-column
                  width="50">
                  <template v-slot="{row, column, $index}">
                    <el-button size="small" icon="el-icon-delete" type="text"
                               @click="removeMoneyCheck($index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-table
                v-else
                :data="moneyForm.request"
                style="width: 100%"
                ref="moneyTable"
              >
                <el-table-column
                  prop="platformId"
                  :show-overflow-tooltip="true"
                  width="200"
                  label="账户ID">
                </el-table-column>
                <el-table-column
                  prop="accountName"
                  :show-overflow-tooltip="true"
                  label="账户名称">
                </el-table-column>
                <el-table-column
                  prop="customerFullName"
                  :show-overflow-tooltip="true"
                  label="客户名称">
                </el-table-column>
                <el-table-column
                  prop="amount"
                  :label="'金额变动'">
                  <template v-if="!isEdit" v-slot="{row}">
                    {{ row.type === 'RECHARGE' ? `+${row.amount}` : `-${row.amount}` }}
                  </template>
                </el-table-column>
                <!--<el-table-column-->
                <!--  prop="requirementName"-->
                <!--  label="需求人"-->
                <!--  v-if="isEdit"-->
                <!--  :formatter="formatterUserName">-->
                <!--</el-table-column>-->
                <el-table-column
                  prop="status"
                  label="状态"
                  :formatter="formatterStatusMix">
                </el-table-column>
                <!--<el-table-column-->
                <!--  prop="createTime"-->
                <!--  label="申请时间"-->
                <!--  :show-overflow-tooltip="true">-->
                <!--</el-table-column>-->
                <el-table-column
                  prop="auditUserName"
                  :show-overflow-tooltip="true"
                  label="审批人">
                </el-table-column>
                <el-table-column
                  prop="auditTime"
                  label="审批时间"
                  :show-overflow-tooltip="true">
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item v-if="!isPlus">
              <el-radio-group v-model="moneyForm.type">
                <el-radio :label="0">自定义</el-radio>
                <el-radio :label="1">全扣</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="moneyForm.type==0&& !isPlus" prop="amount">
              <el-input type="number" oninput="if(value<0)value=0" size="mini" v-model="moneyForm.amount"
                        style="width: 300px"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <template v-slot:bottom>
          <el-button :disabled="btnLoading||moneyForm.request.length === 0" type="primary" v-if="isEdit" size="mini"
                     @click="saveRequest">保存
          </el-button>
          <el-button size="mini" @click="addDrawerSwitch = false">取消</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>
    <!--    查看-->
    <el-drawer
      title="充值记录"
      size="80%"
      :visible.sync="detailDrawer"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :wrapperClosable="false"
    >
      <el-divider></el-divider>
      <cs-drawer-container>
        <div class="account-detail-drawer">
          <el-form label-position="top" label-width="80px" inline>
            <el-form-item>
              <el-date-picker
                size="mini"
                v-model="queryDate"
                type="daterange"
                align="right"
                unlink-panels
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @change="getAccountListByQuery"
              >
              </el-date-picker>

            </el-form-item>
            <el-form-item>
              <el-input size="mini" v-model="queryInput" placeholder="账户ID" @change="getAccountListByQuery"></el-input>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="recordLoading"
            :data="rAccountList"
            style="width: 100%"
            border
            :span-method="spanMethod"
          >
            <el-table-column
              prop="updateTime"
              label="日期"
              width="100">
              <template v-slot="{row}">
                {{ row.updateTime | dateFormat }}
              </template>
            </el-table-column>
            <el-table-column
              prop="platformId"
              :show-overflow-tooltip="true"
              label="账户ID">
            </el-table-column>
            <el-table-column
              prop="accountName"
              :show-overflow-tooltip="true"
              label="账户名称">
            </el-table-column>
            <el-table-column
              prop="customerFullName"
              :show-overflow-tooltip="true"
              label="客户名称">
            </el-table-column>
            <el-table-column
              prop="accountOperator"
              :show-overflow-tooltip="true"
              label="账户运营人">
            </el-table-column>
            <!--<el-table-column-->
            <!--  prop="limits"-->
            <!--  label="账户余额">-->
            <!--</el-table-column>-->
            <el-table-column
              prop="amount"
              :show-overflow-tooltip="true"
              label="金额变动">
              <template v-slot="{row}">
                {{ row.type === 'RECHARGE' ? `+${row.amount}` : `-${row.amount}` }}
              </template>
            </el-table-column>
            <!--<el-table-column-->
            <!--  prop="level"-->
            <!--  label="优先级"-->
            <!--  :show-overflow-tooltip="true"-->
            <!--  :formatter="formatterLevel">-->
            <!--</el-table-column>-->
            <!--<el-table-column-->
            <!--  prop="requirementName"-->
            <!--  label="需求人"-->
            <!--  :show-overflow-tooltip="true"-->
            <!--  :formatter="formatterUserName">-->
            <!--</el-table-column>-->
            <el-table-column
              prop="ttOneAgentTenantName"
              :show-overflow-tooltip="true"
              label="代理">
            </el-table-column>
            <el-table-column
              prop="status"
              label="状态"
              :show-overflow-tooltip="true"
              :formatter="formatterStatusMix">
            </el-table-column>
            <el-table-column
              prop="auditTime"
              label="审批时间"
              :show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column
              prop="auditUserName"
              :show-overflow-tooltip="true"
              label="审批人">
            </el-table-column>
            <!--<el-table-column-->
            <!--  prop="createTime"-->
            <!--  label="申请时间"-->
            <!--  :show-overflow-tooltip="true">-->
            <!--</el-table-column>-->
            <!--<el-table-column-->
            <!--  prop="createUserName"-->
            <!--  :show-overflow-tooltip="true"-->
            <!--  label="创建人">-->
            <!--</el-table-column>-->
          </el-table>
        </div>
        <template v-slot:bottom>
          <el-button size="mini" @click="detailDrawer = false">关闭</el-button>
        </template>
      </cs-drawer-container>
    </el-drawer>
    <!--    编辑-->
    <!--    充值记录-->
  </basic-container>
</template>

<script>
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import CsFilterQuery from '@/components/CsFilterQuery/CsFilterQuery'
import {
  getAccountListByUpdateTime,
  getAccountRechargeRequirementForOne,
  getBCBalance,
  getRecordById,
  getSelectAccountforTT,
  getSelectRechargePlatformAccountsByTTOne,
  getTTAccountBalance,
  saveByBatch,
  saveRechargeByBatch,
  getPredictCost, auditReject,auditRejectByBatch,rechargeSuccessfully,failureRecharge
} from "@/api/accountOrTransfer/transfer";
import {getAllUser} from "@/api/user";
import {mapState} from "vuex";
import _ from 'lodash'

export default {
  name: "MediaForTransfer",
  components: {
    CsDrawerContainer,
    CsFilterQuery
  },
  data() {
    var checkAmount = (rule, value, cb) => {
      if (value >= 10) {
        return cb()
      }

      cb(new Error('金额必须大于10'))
    }
    return {
      StatusSelection:{
        checked1: "",
      },
      checked1:false,
      checked2:false,

      loading: false,
      query: {},
      page: {
        current: 1,
        size: 10,
      },
      threeCostTip:'yesterday',
      sevenCostTip:'yesterday',
      threeDayTip:true,
      sevenDayTip:true,
      total: 0,
      // 新增定时报告弹窗
      addDrawerSwitch: false,
      // 弹窗表头
      drawerTitle: '',
      // 账户列表
      accountList: [],
      // 查看抽屉
      detailDrawer: false,
      // 当前账户
      currentAccountObj: {},
      moneyForm: {
        request: [],
        type: 0,
        amount: ''
      },
      // 所有可选择的账户列表
      selectAccountList: [],
      // 优先级列表
      levelList: [
        {label: '马上', value: 2},
        {label: '当天', value: 1},
        {label: '一般', value: 0},
      ],
      statusList: [
        {
          "label": "新需求",
          "value": 0
        },
        {
          "label": "充值中",
          "value": 1
        },
        {
          "label": "充值成功",
          "value": 2
        }, {
          "label": "充值失败",
          "value": 3
        }, {
          "label": "代理拒绝",
          "value": 4
        }
      ],
      // 所有账户
      allUserList: [],
      // 所有客户
      customerList: [],
      isEdit: false,
      bcBalance: {
        bc_balance: ''
      },
      // 充值
      isPlus: true,
      multipleSelection: [],
      investMoneyList: [],
      rAccountList: [],
      queryDate: null,
      queryInput: '',
      pickerOptions: {},
      btnLoading: false,
      testId:'111',
      rules: {
        amount: [
          {required: true, message: '请输入金额', trigger: 'blur'},
          {validator: checkAmount, trigger: 'blur'}
        ]
      },
      totalMoney: 0,
      // 过滤后的账户id
      filterPlatforIds: [],
      recordLoading: false,
      threeDaysPredictCost:'',
      sevenDaysPredictCost:'',
    }
  },
  watch: {},
  filters: {
    dateFormat(val) {
      return val.substr(0, val.indexOf(' '))
    }
  },
  computed: {
    ...mapState({
      currentUserId: state => state.user.userInfo.user_id // 当前账户的ID
    }),
    // 筛选组件配置
    filterQueryOptions() {
      return [{
        value: 'customerFullName',
        label: '客户'
      }, {
        value: 'amount',
        label: '充值金额',
      }, {
        value: 'platformId',
        label: '账户ID',
        queryList: this.filterPlatforIds
      }, {
        value: 'level',
        label: '优先级',
        children: this.levelList
      },
      //   {
      //   value: 'status',
      //   label: '充值状态',
      //   children: this.statusList
      // }
      ];
    },
  },
  created() {
    this.StatusSelection.checked1 = 0
    this.getAccountList()
    this.getSelectAccountList()
    this.getAllUserList()
    this.getFilterPlatformIds()
    this.getBalance()
    this.getPredictCostFun()
  },
  mounted(){

  },
  methods: {
    newStatus(){
      this.query.status = this.StatusSelection.checked1
      // this.query=this.checked1 ? {status:0} : ''
      this.getAccountList()
    },
    newStatus1(){
      if(!this.checked1 && this.checked2)this.query={status:1}
      if(this.checked1 && this.checked2) this.query={status:'0,1'}
      if(this.checked1 && !this.checked2)this.query={status:0}
      if(!this.checked1 && !this.checked2)this.query=''
      this.getAccountList()

    },
    uploadAccount(){
      this.getAccountList()
    },
    handleChangeFilter(val) {
      // console.log(val.amount,isNaN(val.amount))
      if (val.amount !== undefined && isNaN(val.amount)) return
      this.query = val
      this.query.status = this.StatusSelection.checked1
      this.page.current = 1
      this.getAccountList()
      // console.log('guo',val)
    },
   async getPredictCostFun(){
    const {data: res } =  await getPredictCost()
       this.threeDaysPredictCost=res.data.threeDaysPredictCost
       this.sevenDaysPredictCost=res.data.sevenDaysPredictCost
    },
    predictCostTip(){
      if (parseFloat(this.bcBalance.bc_balance)<=parseFloat(this.threeDaysPredictCost)){
        this.threeDayTip = false
        this.threeCostTip = 'textDecorate'
      }
      if (parseFloat(this.bcBalance.bc_balance)<=parseFloat(this.sevenDaysPredictCost)){
        this.sevenDayTip = false
        this.sevenCostTip = 'textDecorate'
      }
    },
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getAccountList()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.getAccountList()
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取账户列表
    async getAccountList() {
      this.loading = true
      this.query.status = this.StatusSelection.checked1
      const {data: res} = await getAccountRechargeRequirementForOne({
        ...this.page,
        ...this.query
      }).finally(() => {
        this.loading = false
      })
      this.total = res.data.total
      this.accountList = res.data.records
    },
    // 查看详情
    showDetail() {
      this.detailDrawer = true
      this.getAccountListByQuery()
    },
    async getAccountListByQuery() {
      this.recordLoading = true
      const {data: res} = await getAccountListByUpdateTime({
        startDate: this.queryDate ? this.queryDate[0] + ' 00:00:00' : null,
        endDate: this.queryDate ? this.queryDate[1] + ' 00:00:00' : null,
        platformId: this.queryInput
      }).finally(() => {
        this.recordLoading = false
      })
      this.rAccountList = res.data
    },
    // 移除指标
    removeMoneyCheck(index) {
      this.moneyForm.request.splice(index, 1)
    },
    // 获取tt账户
    async getSelectAccountList() {
      const {data: res} = await getSelectAccountforTT()
      this.selectAccountList = res.data
    },
    // 获取账户名称
    filterAccountsInfo(event, row) {
      const account = this.selectAccountList.find(item => item.id === event)
      // console.log(account)
      row.accountName = account.name
      row.customerFullName = account.customerFullName
      row.platform = account.platform
      row.accountOperator = account.operatorName
    },
    async getAllUserList() {
      const res = await getAllUser({statusList: '0,1,2', isAll: true})
      this.allUserList = res.data.data.map(item => {
        return {
          label: item.realName,
          value: item.id
        }
      })
    },
    // 保存充值扣减
    saveRequest() {
      this.$refs.moneyForm.validate(async valid => {
        if (!valid) return
        this.btnLoading = true
        if (this.isPlus) {
          const ids = this.moneyForm.request.map(item => item.id).join(',')
          const {data: res1} = await saveRechargeByBatch(ids).finally(() => {
            this.btnLoading = false
            this.addDrawerSwitch = false
          })
          if (res1.code !== 200) return
          this.$message.success('充值成功')
        } else {
          const temp = _.cloneDeep(this.moneyForm.request)
          const accounts = temp.map(item => {
            item.refundType = this.moneyForm.type
            if (this.moneyForm.type === 0) {
              item.amount = this.moneyForm.amount
            } else {
              item.amount = null
            }
            return item
          })
          const {data: res2} = await saveByBatch(accounts).finally(() => {
            this.btnLoading = false
            this.addDrawerSwitch = false
          })
          if (res2.code !== 200) return
          if (res2.data.refundFailPlatforms.length > 0) {
            const html = res2.data.refundFailPlatforms.reduce(function (total, currentVal) {
              return total + `<div>${currentVal.platformId}<div></div>${currentVal.errorMsg}</div><br/>`
            }, '')
            this.$alert(html, '扣减失败!', {
              confirmButtonText: '确定',
              dangerouslyUseHTMLString: true
            });
          } else {
            this.$message.success('扣减成功')
          }
        }
        await this.getAccountList()

      })

    },
    // 查看充值记录
    async getRecordById(row) {
      this.isEdit = false
      this.isPlus = true
      const {data: res} = await getRecordById(row.platformId)
      // console.log(res.data)
      if (res.code !== 200) return
      this.moneyForm.request = res.data
      this.addDrawerSwitch = true
    },
   async auditReject(row){
      const {data:res}= await auditReject({id:row.id,status:row.status})
     if(res.code===200){
       this.$message.success('代理拒绝')
       await this.getAccountList()
     }
    },
    //充值成功
    async rechargeSuccessfullyClick(ids){
      const {data:res}= await rechargeSuccessfully(ids);
      if(res.code===200){
        this.$message.success('充值成功')
        await this.getAccountList();
      }
    },
    //批量充值成功
    async batchRechargeSuccessfully(){
      if (!this.multipleSelection.length){
        return this.$message.warning('请勾选数据！')
      }
      let ids = (this.multipleSelection.map(item=>item.id)).join(',')
      await this.rechargeSuccessfullyClick(ids)
    },
    //充值失败
    async failureRechargeClick(ids){
      const {data:res}= await failureRecharge(ids);
      if(res.code===200){
        this.$message.success('充值失败')
        await this.getAccountList();
      }
    },
    //批量充值失败
    async failureRecharge(){
      if (!this.multipleSelection.length){
        return this.$message.warning('请勾选数据！')
      }
      let ids = (this.multipleSelection.map(item=>item.id)).join(',')
      await this.failureRechargeClick(ids)
    },
    //批量拒绝
    async reviewReject(){
      if (!this.multipleSelection.length){
       return this.$message.warning('请勾选数据！')
      }
      let ids = (this.multipleSelection.map(item=>item.id)).join(',')
      await this.batchAuditReject(ids)
    },
    // 审核拒绝方法
    async batchAuditReject(ids){
      const {data:res}= await auditRejectByBatch(ids);
      if(res.code===200){
        this.$message.success('拒绝成功')
        await this.getAccountList();
      }
    },
    //审核通过方法
    async auditPass(ids){
      const {data:res}= await saveRechargeByBatch(ids)
      if(res.code===200){
        this.$message.success('审核通过');
        await this.getAccountList()
      }
    },
      formatterStatus(row, column, cellValue, index) {
      const temp = this.statusList.find(item => item.value === cellValue)
      if (temp === undefined) {
        return ''
      } else {
        return temp.label
      }
    },
    formatterStatusMix(row, column, cellValue, index) {
      if (row.type === 'RECHARGE') {
        switch (row.rechargeStatus) {
          case 0:
            return '新需求'
          case 1:
            return '充值中'
          case 2:
            return '充值成功'
          case 3:
            return '充值失败'
          default:
            return '未知参数'
        }
      } else {
        switch (row.refundStatus) {
          case 0:
            return '创建扣款'
          case 1:
            return '充值中'
          case 2:
            return '扣款成功'
          case 3:
            return '扣款失败'
          default:
            return '未知参数'
        }
      }
    },
    // 账户名称
    formatterUserName(row, column, cellValue, index) {
      const temp = this.allUserList.find(item => item.value === cellValue)
      if (temp === undefined) {
        return ''
      } else {
        return temp.label
      }
    },
    // 有优先级
    formatterLevel(row, column, cellValue, index) {
      const temp = this.levelList.find(item => item.value === cellValue)
      if (temp === undefined) {
        return ''
      } else {
        return temp.label
      }
    },
    // 获取余额
    async getBalance() {
      const {data: res} = await getBCBalance()
      this.bcBalance = res.data
      this.predictCostTip()
    },
    //审核通过
    async approvedReview(){
      if(this.multipleSelection.length === 0){
        return this.$message.warning('请先勾选数据')
      }else {
        let arrIds = (this.multipleSelection.map(item =>{return item.id})).join(',')
        await this.auditPass(arrIds)
      }
    },
    // 批量充值/扣减
    async multipleInvestMoney(isPlus) {
      const isTiktok = this.multipleSelection.some(item => item.platform != 'tiktok')
      if(isTiktok === true){
        if(isPlus){
          return this.$message.warning('只支持Tiktok平台批量处理，其它平台通过需手动填写账户ID')
        }else{
          return this.$message.warning('只支持Tiktok账户')
        }
      }else{
        this.multipleSelection.forEach((item)=>{
          if(item.platform !== 'tiktok'){
            this.$message.warning('只支持Tiktok平台批量处理，其它平台通过需手动填写账户ID')
            return false
          }
        })
        if (this.multipleSelection.length === 0) return this.$message.warning('请先勾选数据')
        if (isPlus) {
          if (this.multipleSelection.some(item => item.status !== 0)) return this.$message.warning('充值状态必须是新需求')
        }
        this.isPlus = isPlus
        this.isEdit = true
        this.totalMoney = this.multipleSelection.reduce(function (total, curVal) {
          return total + Number(curVal.amount)
        }, 0)
        const arr = this.multipleSelection.map(async item => {
          const {data: {data}} = await getTTAccountBalance(item.platformId)
          item.limits = data
          return item
        })
        this.moneyForm.request = await Promise.all(arr)
        this.addDrawerSwitch = true
      }

    },
    // 充值/扣减
    async investMoney(isPlus, row) {
      this.isPlus = isPlus
      this.isEdit = true
      this.totalMoney = row.amount
      const {data: {data}} = await getTTAccountBalance(row.platformId)
      row.limits = data
      this.moneyForm.request = [row]
      this.addDrawerSwitch = true
    },
    // 合并单元格
    spanMethod({row, column, rowIndex, columnIndex}) {
      const same = this.rAccountList.filter(item => item.updateTime === row.updateTime)
      if (same.length >= 2) {
        same.forEach((item, index) => {
          if (!item.hasOwnProperty('row')) {
            if (index === 0) {
              item.row = same.length
            } else {
              item.row = 0
            }
          }
        })
      }
      if (columnIndex === 0) {
        if (row.hasOwnProperty('row')) {
          return {
            rowspan: row.row,
            colspan: 1
          }
        }
      }
    },
    // 关闭充值记录侧边栏周期函数
    closeRecordsDrawer() {
      this.moneyForm.amount = ''
    },
    async getFilterPlatformIds() {
      const {data: res} = await getSelectRechargePlatformAccountsByTTOne()
      this.filterPlatforIds = res.data.map(item => {
        return {
          label: item,
          value: item
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-card__header {
  border-bottom: unset;
}

.curd-table {
  .tab-header {
    font-size: 14px;
    margin-bottom: 15px;

    .tab-header-left {
      float: left;

      & > * {
        margin-right: 15px;
      }
    }

    .tab-header-right {
      float: right;
    }
  }

  .bottom-page {
    margin-top: 15px;
    margin-bottom: 50px;

    .el-pagination {
      float: right;
    }
  }
}

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}

.cs-button {
  cursor: pointer;
  font-size: 16px;
}

.active {
  color: #409EFF;
}

.disabled {
  cursor: default !important;
}

.account-detail-drawer {
  padding: 0 20px;
}

.add-money-box {
  padding: 0 15px;
}

.header {

  .header-up {
    display: flex;
    justify-content: space-between;

    .date-template {
      .dt-item {
        display: inline-block;
        margin-bottom: 10px;
        margin-right: 10px;
      }
    }

    .yesterday {
      color: green;
    }
    .textDecorate {
      color: red;
      text-decoration: underline;
    }
  }

}

.push-money-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  font-size: 14px;

  .push-money-info-left {
    color: #1684FD;
  }
}
</style>
